<?php
	// Make sure we're logged in (send us to the front page if not)
	gatekeeper();

  // Make sure action is secure
  action_gatekeeper();
  
	// Get input data
  $destinataires = get_input('autobox');
  $message = get_input('message');
  $guid = get_input('guid');
	$type = get_input('type');
	
  $acces=2;

  $entity=get_entity($guid);
	if($entity->canEdit()){
		$entity->access_id=$acces;
		$entity->save();
		$entity->validate="valide";
	}
		$url= $entity->getURL()."?validate=true";
		$message.="Le ".$type." a valider est : <a href='". $url."'>". $entity->title."  </a>";
   
  //verifions si la collection existe
	$collections=get_user_access_collections($_SESSION['user']->getGUID());
  $exist= false;
  $validateurguid='';
  $validateurcollection='Validateurs';
  // regarder si le groupe existe
  foreach($collections as $c)
  {
    if($c->name==$validateurcollection){
      $exist=true;
      $validateurguid=$c->id;
      $acces=$c->id;
    }
  }
	
  //créer le gorupe si il n'existe pas
  if($exist!=true)
  {
    $validateurguid=create_access_collection($validateurcollection,$_SESSION['user']->guid);
  }
	
  $destinataires = string_to_tag_array($destinataires);

  //pour chaque destinataire
  foreach($destinataires as $d)
  {
		$friend=false;
    $friends=get_user_friends($_SESSION['user']->guid);
    //vérifier si c'est un contact
    foreach($friends as $f)
    {
      if($f->guid==$d){
        $friend=true;
      }
    }		
   if(!$friend){
     //ajouter le contact
      $_SESSION['user']->addFriend($d); 		
      add_user_to_access_collection($d,$validateurguid);
    }
    else{
      //verifier si il appartient d�j� au groupe sinon l'ajouter
      $membersvalidateur=get_members_of_access_collection($validateurguid);
			if(empty($membersvalidateur))
				add_user_to_access_collection($d,$validateurguid);
			else{
				foreach( $membersvalidateur as $m)
				{
					if($m->guid != $d){
						add_user_to_access_collection($d,$validateurguid);
					}
				}
			}
    }
		
   //envoi du message
    
    $title='Demande de Validation de '. $_SESSION['user']->name;			
		$result = messages_send($title,$message,$d,0);
			
	    // Save 'send' the message
			if (!$result) {
				register_error(elgg_echo("messages:error"));
				forward("mod/messages/send.php");
			} 
  }

  forward("/pg/riverdashboard/");
?>
